<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Signup as SignupModel;
use app\common\model\Meeting as MeetingModel;

/**
 * 首页接口
 */
class Signup extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

	protected $model,$meetingModel;

	public function _initialize()
    {
        parent::_initialize();
		$this->model = new SignupModel();
		$this->meetingModel = new MeetingModel();
	}

    public function save()
    {
		// 处理提交
		if($this->request->isPost()){
			$meeting = $this->meetingModel->find($this->request->post('meeting_id'));

			$sign_type = $this->request->post('sign_type');
			if($sign_type == 1){
				// 付费参观
				$pay_status = 0;
				$discount = rand(0,$meeting->discount);
				$amount = $meeting->price - $discount;
			}else{
				// 免费参观
				$pay_status = 1;
				$amount = 0;
			}

			// 整合提交数据
			$datas = [
				'__token__' => $this->request->token(),
				'meeting_id' => $this->request->post('meeting_id'),
				'name' => $this->request->post('name'),
				'mobile' => $this->request->post('mobile'),
				'group' => $this->request->post('group'),
				'pay_type' => $this->request->post('pay_type'),
				'sign_type' => $sign_type,
				'pay_status' => $pay_status,
				'amount' => $amount,
			];

			// 验证
			$validate = validate('Signup');
			if($validate->scene('save')->check($datas)){
				unset($datas['__token__']);
				//数据唯一性
				$signup = $this->model->where(['mobile' => $datas['mobile'],'meeting_id' => $this->request->post('meeting_id')])->find();
				if(!$signup){
					$result = $this->model->save($datas);
					if($result){
						$signup = $this->model;
					}else{
						$this->error('报名失败，请重试',['url' => 'index/signup/index']);
					}
				}else{
					$signup->name = $datas['name'];
					$signup->group = $datas['group'];
					$signup->pay_type = $datas['pay_type'];
					if($signup->sign_type == 0 && $sign_type == 1){
						// 免费参加改付费参加
						$signup->sign_type = $sign_type;
						$signup->pay_status = $pay_status;
						$signup->amount = $amount;
						$signup->save();
					}elseif($signup->sign_type == 1 && $sign_type == 0){
						// 付费参加改免费参加
						if($signup->pay_status == 0){
							$signup->sign_type = $sign_type;
							$signup->pay_status = $pay_status;
							$signup->amount = $amount;
						}
						$signup->save();
						$this->success('请求成功',['url' => url('index/signup/order',['id' => $signup->id])]);
					}
				}
			}else{
				$this->error($validate->getError());
			}
		}

//        $this->success('请求成功',['url' => url('index/signup/pay',['id' => $signup->id])]);
        $this->success('请求成功',['url' => url('index/signup/order',['id' => $signup->id])]);
    }
}
